package com.willian.andrappfw.network;

import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.willian.andrappfw.utils.WPreferenceManager;


public abstract class WCacheCallback<T> extends WBaseCallback<T> {
    public static Gson gson = new Gson();

    @Override
    public final void onFailure(Throwable throwable) {
        String jsonStr = WPreferenceManager.getInstance().getString(getCacheKey(), null);
        if (jsonStr != null) {
            T cacheData = getCacheData(jsonStr);
            if (cacheData != null) {
                onSucceed(cacheData);
            }
        }
    }

    @Override
    @CallSuper
    public void onSucceed(T data) {
        WPreferenceManager.getInstance().edit().putString(getCacheKey(), new Gson().toJson(data)).apply();
    }

    public abstract String getCacheKey();

    public abstract T getCacheData(@NonNull String jsonStr);
}
